<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/9/2
 * Time: 10:46
 */

namespace App\Services;


use App\HttpController\UserGroup;
use App\Model\MsgModel;
use App\Model\UserGroupModel;
use App\Model\UserModel;
use EasySwoole\EasySwoole\Config;

class SystemMessageService
{
    /**
     * 邀请入群主动推送
     * showdoc
     * @catalog Websocket/服务端主动推送
     * @title  服务端主动推送
     * @description   根据msg_id，主动推送系统消息
     * @param extra.msg_id 是 string 消息id，如果客户端请求，则服务端会主动推送该消息到客户端，这个服务只对系统消息有效
     * @return {"code":200,"result":'',"msg":"sucess"}
     * @return_param  code int 状态码(200:成功0:失败400:未登录)
     * @return_param  member_list array 被邀请入群的成员列表
     * @return_param  group_info array 群信息
     * @remark 2020-09-09
     */


    /**推送系统消息
     * @param $param
     * @param $userInfo
     */
    public function sendSysmessage($param,$userInfo){
        try{
            $message = MsgModel::create()->get(['id'=>$param['extra']['msg_id']]);
            $msgService = new MsgService();
            if(empty($message)){
                return ReponseCodeService::CODE_FAILE;
            }
            if($message['sub_type']==2){
                $sysMessage = array(
                    'group_id'=> $message['to_id'],
                    'content'=>'',
                    'app_id'=>$userInfo['app_id'],
                    'type'=>$message['type'],
                    'extra'=>json_decode($message['extra'],true),
                    'msg_id'=>$message['id'],
                    'nonce'=>$message['nonce']
                );
                $this->groupSysMessage($sysMessage);
            }else{#个人系统消息



            }

            return ReponseCodeService::CODE_OK;

        }catch(\Throwable $t){
            echo $t->getMessage();
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }




    /**发送群的系统消息，这边是实时发送的，没收到的走离线消息
     * @param $groupSysMessage
     */
    public function groupSysMessage($groupSysMessage){
        $data = array(
            'group_id' =>$groupSysMessage['group_id'],
            'content'=>$groupSysMessage['content'],
            'type'=>$groupSysMessage['type'],
            'extra'=>$groupSysMessage['extra'],
            'sub_type'=>MsgModel::MSG_SUB_TYPE_GROUP,
        );
        //消息入库
        $insertData['user_id'] = 0;
        $insertData['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
        $insertData['to_id'] = $groupSysMessage['group_id'];
        $insertData['msg'] = $groupSysMessage['content'];
        $insertData['app_id'] = $groupSysMessage['app_id'];
        $insertData['extra'] = json_encode($groupSysMessage['extra']);
        $insertData['type'] = $groupSysMessage['type'];
        $insertData['created_at'] =HelpService::msectimeToStr(HelpService::msectime());
        $insertData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
        try{
            if(!isset($groupSysMessage['msg_id'])||empty($groupSysMessage['msg_idid'])){
                $msgId = MsgModel::create()->data( $insertData)->save();
            }else{
                $msgId = $groupSysMessage['msg_id'];
            }
        }catch(\Throwable $t){
            echo $t->getMessage();
            echo '无法生成id';
            return false;
        }

        $messageArr = array(
            'code'=>ReponseCodeService::CODE_OK,
            'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
            'data'=>json_encode($data),
            'action'=>'systemMessage',
            'nonce'=>$groupSysMessage['nonce'],
            'time'=>HelpService::msectime(),
            'msg_id'=>$msgId,
            'group_id'=>$groupSysMessage['group_id']
        );

        //发布订阅
        $redisPool = \EasySwoole\RedisPool\Redis::getInstance()->get('redis');
        $redis = $redisPool->getObj();
        $redis->publish(Config::getInstance()->getConf('CHAT.group_chat'),json_encode($messageArr));
        $redisPool->recycleObj($redis);
        return $messageArr;
    }

    /**推送个人系统消息
     * @param $sysMessage
     */
    public function privateSysMsg($message,$userInfo){
        try{
            $userWhere =[
                'app_id'=>$userInfo['app_id'],
                'to_app_user_id'=>$message['to_app_user_id']
            ];
           $toUserInfo = UserModel::create()->get($userWhere);
           if(empty($toUserInfo)){
               return ReponseCodeService::CODE_FAILE;
           }
        }catch(\Throwable $t){
            echo $t->getMessage();
            return false;
        }

        $data = array(
            'to_user_id'=> $toUserInfo['id'],
            'to_app_user_id'=>$message['to_app_user_id'],
            'content'=>$message['content'],
            'type'=>$message['type'],
            'extra'=>$message['extra'],
            'sub_type'=>MsgModel::MSG_SUB_TYPE_PERSONAL,
        );


        //消息入库
        $insertData['user_id'] = 0;
        $insertData['sub_type'] = MsgModel::SUB_TYPE_PRY_SYS_MSG;
        $insertData['to_id'] = $toUserInfo['id'];
        $insertData['msg'] = $message['content'];
        $insertData['app_id'] = $userInfo['app_id'];
        $insertData['extra'] = json_encode($message['extra']);
        $insertData['type'] = $message['type'];
        $insertData['created_at'] =HelpService::msectimeToStr(HelpService::msectime());
        $insertData['updated_at'] = HelpService::msectimeToStr(HelpService::msectime());
        try{
            if(!isset($messagee['msg_id'])||empty($message['msg_id'])){
                $msgId = MsgModel::create()->data( $insertData)->save();
            }else{
                $msgId = $message['msg_id'];
            }
        }catch(\Throwable $t){
            echo $t->getMessage();
            echo '无法生成id';
            return false;
        }

        $messageArr = array(
            'code'=>ReponseCodeService::CODE_OK,
            'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
            'data'=>json_encode($data),
            'action'=>'systemMessage',
            'nonce'=>$message['nonce'],
            'time'=>HelpService::msectime(),
            'msg_id'=>$msgId,
            'user_id'=>$toUserInfo['id']
        );
        
    }

    /**
     * 同步群系统消息
     */
    public function syncGroupsysMsg($userInfo){
        try{
            $userGroupWhere = array(
                'user_id'=>$userInfo['id'],
                'status' => UserGroupModel::STATUS_NORMAL
            );

            $userGroupArr = UserGroupModel::create()->where($userGroupWhere )->column('group_id');
            #没有需要同步的，直接认为成功
            if(empty($userGroupArr)){
                echo '没有群系统消息要同步'.PHP_EOL;
                return true;
            }
            echo '一共'.count($userGroupArr).'个群'.PHP_EOL;

            $where  = array(
                 'to_id'=>[$userGroupArr,'in']
            );
            #补推送登录到正常状态的系统消息
            $redisPool = \EasySwoole\RedisPool\Redis::getInstance()->get('redis');
            $redis = $redisPool->getObj();
            if(!empty($redis)){
                $userService = new UserService();
                $toUserInfo = $userService->getUserOnlineInfo($userInfo['id']);
                if(empty($toUserInfo)){
                    return false;
                }
                $startTime = HelpService::msectimeToStr($toUserInfo['login_time']);
            }else{
                $startTime = '';
            }

            if(!empty($startTime)){
                $where['created_at'] = [$startTime,'>'];
            }
            $where['sub_type'] = MsgModel::SUB_TYPE_GOUP_SYS_MSG;
            $page = 1;          // 当前页码
            $limit = 100;        // 每页多少条数据
            $model =MsgModel::create()->limit($limit * ($page - 1), $limit)->withTotalCount();
            $list = $model->all($where);
            $result = $model->lastQueryResult();
            $total = $result->getTotalCount();
            $totalPage = ceil($total/$limit);
            $pushMessageService = new PushMessageService();

            if(!empty($list)){
                echo '非空'.PHP_EOL;
                while ($page<=$totalPage){
                    foreach ($list as $message){
                        $msgId = $message['id'];
                        echo    '群系统消息id:'.$msgId.PHP_EOL;
                        $data = array(
                            'group_id' => $message['to_id'],
                            'content'=>$message['content'],
                            'type'=>$message['type'],
                            'extra'=>json_decode($message['extra']),
                            'sub_type'=>MsgModel::MSG_SUB_TYPE_GROUP,
                        );
                        $messageArr = array(
                            'code'=>ReponseCodeService::CODE_OK,
                            'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
                            'data'=>json_encode($data),
                            'action'=>'systemMessage',
                            'nonce'=>$message['nonce'],
                            'time'=>HelpService::msectime(),
                            'msg_id'=>$msgId,
                            'group_id'=>$message['to_id']
                        );
                        $pushMessageService->push($toUserInfo['fd'],$messageArr);
                    }
                    $page = $page+1;
                    $model =MsgModel::create()->limit($limit * ($page - 1), $limit)->withTotalCount();
                    $list = $model->all($where);
                }
            }
           return  true;
        }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**
     * 同步个人系统消息、只同步添加好友
     */
    private function syncPrivateSysMsg($userInfo){
        try{
            #补推送登录到正常状态的系统消息
            $redisPool = \EasySwoole\RedisPool\Redis::getInstance()->get('redis');
            $redis = $redisPool->getObj();
            if(!empty($redis)){
                $userService = new UserService();
                $toUserInfo = $userService->getUserOnlineInfo($userInfo['id']);
                if(empty($toUserInfo)){
                    return false;
                }
                $startTime = HelpService::msectimeToStr($toUserInfo['login_time']);
            }else{
                $startTime = '';
            }
            $where = array();
            if(!empty($startTime)){
                $where['created_at'] = [$startTime,'>'];
            }
            $where['to_id'] = $userInfo['id'];
            $where['sub_type'] = MsgModel::SUB_TYPE_PRY_SYS_MSG;
            $where['status']  = MsgModel::STATUS_NON_DELIVERY;
            $page = 1;          // 当前页码
            $limit = 100;        // 每页多少条数据
            $model =MsgModel::create()->limit($limit * ($page - 1), $limit)->withTotalCount();
            $list = $model->all($where);
            $result = $model->lastQueryResult();
            $total = $result->getTotalCount();
            $totalPage = ceil($total/$limit);
            $pushMessageService = new PushMessageService();

            if(!empty($list)){
                echo '非空'.PHP_EOL;
                while ($page<=$totalPage){
                    foreach ($list as $message){
                        $msgId = $message['id'];
                        echo    '个人系统消息id:'.$msgId.PHP_EOL;
                        $data = array(
                            'user_id' => $message['to_id'],
                            'content'=>$message['content'],
                            'type'=>$message['type'],
                            'extra'=>json_decode($message['extra']),
                            'sub_type'=>MsgModel::MSG_SUB_TYPE_GROUP,
                        );
                        $messageArr = array(
                            'code'=>ReponseCodeService::CODE_OK,
                            'msg'=>ReponseCodeService::$phrases[ReponseCodeService::CODE_OK],
                            'data'=>json_encode($data),
                            'action'=>'systemMessage',
                            'nonce'=>$message['nonce'],
                            'time'=>HelpService::msectime(),
                            'msg_id'=>$msgId,
                            'user_id'=>$message['to_id']
                        );
                        $pushMessageService->push($toUserInfo['fd'],$messageArr);
                        #修改消息状态
                        MsgModel::create()->update(['status'=>MsgModel::STATUS_DELIVERED],['id'=>$message['id']]);
                    }
                    $page = $page+1;
                    $model =MsgModel::create()->limit($limit * ($page - 1), $limit)->withTotalCount();
                    $list = $model->all($where);
                }
            }
            return  true;
        }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }
    /**
     * 同步系统消息
     */
    public function syncSystemMsg($userInfo){
        #同步群系统消息
        go(function ()use($userInfo){
            $this->syncGroupsysMsg($userInfo);
        });
        #同步单聊系统消息
        go(function ()use($userInfo){
            $this->syncPrivateSysMsg($userInfo);
        });

    }



}